from rest_framework.response import Response
from rest_framework.views import APIView
from User.sers import *


class UploadView(APIView):
    def post(self, request):
        # 接受页面上传的数据
        grade = request.data.get('grade', '')
        client = request.data.get('client', '')
        if all([grade, client]):
            pass
        else:
            return Response({'msg': '缺少参数', 'code': 0})
        if grade:
            # 获取数据库的数据
            old_grade = Grade.objects.filter(client=client).first()
            if old_grade:
                if old_grade.grade != grade:
                    old_grade.grade = grade
                    old_grade.save()
            else:
                Grade.objects.create(client=client, grade=grade)

            # 排名表数据更新
            Rank.objects.all().delete()
            grade_li = [score_obj.id for score_obj in Grade.objects.all().order_by('-grade')]
            n = 1
            for i in grade_li:
                Rank.objects.create(g_id_id=i, rank=n)
                n = n + 1
            return Response({'msg':'成功','code':999})
        return Response({'msg':'error','code':0})


# 查询
class ShowAPIView(APIView):
    def get(self, request):
        # 接收用户传入的区间
        num1 = request.GET.get('num1')
        num2 = request.GET.get('num2')
        user_id = request.GET.get('uid')
        Rank_queryset = Rank.objects.filter(rank__gte=num1,rank__lte=num2).order_by('rank')
        rank_list = []
        for i in Rank_queryset:
            rank_list.append({'id':i.rank,'client':i.g_id.client,'grade':i.g_id.grade})
        # 拿到查询用户的信息和排名
        user = Grade.objects.get(id=user_id)
        user_ran = Rank.objects.get(g_id=user_id).rank
        rank_list.append({'id':user_ran,'client':user.client,'grade':user.grade})
        return Response({'msg':'成功', 'rank_list':rank_list})
